﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using Gueei.Gallery.Core.Repositories;
using Newtonsoft.Json;

using Gueei.Gallery.Core.Entities;
using Newtonsoft.Json.Linq;

namespace Gueei.Gallery.Web
{
	public class JsonImageRepository:IImageRepository
	{
		private readonly List<Image> _images;

		public JsonImageRepository(string jsonDir)
		{
			Directory.CreateDirectory(jsonDir);
			JsonFilePath = Path.Combine(jsonDir, "images.js");
			if (File.Exists(JsonFilePath))
			{
				try
				{
					string json = "";
					using (var fs = new StreamReader(JsonFilePath))
					{
						json = fs.ReadToEnd();
					}
					_images = JsonConvert.DeserializeObject<List<Image>>(json);
				}
				catch
				{
					_images = new List<Image>();
				}
			}
			else
			{
				_images = new List<Image>();
			}
		}
		protected string JsonFilePath
		{
			get;
			set;
		}

		public IQueryable<Core.Entities.Image> GetImages()
		{
			return _images.AsQueryable();
		}


		public Image SaveImage(Image image, bool overwrite)
		{
			if (!ImageExists(image.Id))
				_images.Add(image);
			else if (!overwrite)
				throw new ArgumentException("Image already existed. ");

			var json = JsonConvert.SerializeObject(_images);
			using (var fs=new StreamWriter(JsonFilePath))
			{
				fs.WriteLine(json);
			}
			return image;
		}

		public Image GetImage(Guid id)
		{
			return GetImages().Where(i => i.Id.Equals(id)).FirstOrDefault();
		}

		public bool ImageExists(Guid id)
		{
			return GetImage(id) != null;
		}
	}
}
